<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Console\Commands\WdtClient;
use App\Services\WdtStockSync;
use App\Http\Controllers\Api\OrderController;

//
//实时同步库存回写到旺店通api 修改为定期商品刷新同步库存到旺店通  5min
//接口描述：库存量同步至平台是否成功的状态批量回传给旺店通ERP   注：仅支持自有/其他平台店铺
// 文档地址: https://open.wangdian.cn/open/apidoc/doc?path=api_goods_stock_change_ack.php
//测试执行命令  php artisan sync:GoodsStockChangeAck

class SyncGoodsStockChangeAck extends Command
{
    protected $signature = 'sync:GoodsStockChangeAck';
    protected $description = '实时同步库存回写到旺店通api';

    // 实时同步库存回写，每次推送一批库存同步状态
    public function handle()
    {
        Log::info('同步任务SyncGoodsStockChangeAck', ["开始全量推送goods库存到旺店通"]);
        $sid = config('services.wdt.sid');
        $appkey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'api_goods_stock_change_ack.php';

        $c = new WdtClient($sid, $appkey, $secret, $url);

        // 1. 查询所有商品
        $goodsList = \App\Models\Admin\Goods::select(['id', 'goods_sale_num'])->get();
        $batchSize = 20;
        $total = $goodsList->count();
        $this->info('goods商品总数: ' . $total);

        $goodsArr = $goodsList->toArray();
        $batches = array_chunk($goodsArr, $batchSize);

        foreach ($batches as $batch) {
            $stock_sync_list = [];
            foreach ($batch as $goods) {
                if (!empty($goods['rec_id'])) {
                    $stock_sync_list[] = [
                        'rec_id' => $goods['rec_id'],
                        'sync_stock' => $goods['goods_sale_num'],
                        'stock_change_count' => time(), // 或者用 0
                    ];
                }
            }
            Log::info('旺店通库存同步回请求旺店通参数', [$stock_sync_list]);
            $c->putApiParam('stock_sync_list', json_encode($stock_sync_list, JSON_UNESCAPED_UNICODE));
            $result = $c->wdtOpenApi();
            Log::info('旺店通库存同步回写结果', [$result]);
        }

        $this->info('库存同步回写任务执行完毕');
    }
} 